<template>
  <!-- 客档合并 -->
  <div>
    <TopFilter
      :list="topFilterList"
      :cols="3"
      labelWidth="100"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>

    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :onColumnsChange="columns => this.columns = columns"
      :onRowSelectChange="selectChangeHandle"
      :defaultSelections="selectedList"
      columnsRef="potenCus_customer_mergeCustomer_index_01"
    >
      <template slot="controls" >
        <el-button size="small" type="primary" @click="mergeListHandle">加入合并列表</el-button>
        <el-button
          size="small"
          type="primary"
          :disabled="willingToMergeData.length == 0"
          @click="mergeHandle"
        >合并</el-button>
      </template>
    </FilterTable>
    <BaseDialog
      :visible.sync="visible"
      :title="dialogTitle"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <MergeModel :rowData="willingToMergeData" @close="closeHandler" @selected="selected" />
    </BaseDialog>
  </div>
</template>

<script>
import { clueMarkftinhView } from '@/api/potenCus/customer/cluesQuery';
import { getUserInfo } from '@/api/potenCus/customer/exhibition';
import { getAllModal, queryClueSourceList, getConsultantName, getAllHeatUp } from '@/api/potenCus/customer/potenCusManage';
import { vehicleConfiguration, vehicleConfigurationNew } from '@/api/retail/salesmanage/confirmcar'; //获取五级菜单
import { dictionary } from '@/utils/dictMixin';
import { authority } from '@/utils/authMixin';
import MergeModel from './mergeModel';
import moment from 'moment';
export default {
  name: 'mergeCustomer',
  mixins: [dictionary, authority],
  components: {
    MergeModel
  },
  data() {
    return {
      topFilterList: this.createTopFilters(),
      fetchParams: { allot: 3 },
      dialogTitle: '选择主客档',
      fetchApi: clueMarkftinhView,
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      conf: { add: '新增' },
      selectedRows: [], // 列表选中行
      willingToMergeData: [], // 合并数据
      selectedList: [], // 移除数据
      visible: false //
    };
  },
  created() {
    this.init();
    this.getAllHeatUp();
  },
  methods: {
    async init() {
      // 车型
      vehicleConfigurationNew(0, { isUnlimited: 10041001 })
        .then(res => {
          this.topFilterList.find(item => item.fieldName === 'inteCarType').itemList = res.data;
        })
        .catch(err => {
          // console.log(err)
        });
      // // 查询所属顾问
      let roleType = this.dataType === 'clue' ? '10061012' : '10061012,10061015';
      this.getConsultant(1, roleType).then(result => {
        this.topFilterList.find(item => item.fieldName === 'consultants').itemList = result;
      });
    },
    async getAllHeatUp() {
      const res = await getAllHeatUp({ isValid: 10041001 });
      console.log('线索热度定义', res);
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'temperatures').itemList = res.data.map(x => ({ value: x.id, text: x.clueHeatName }));
      }
    },
    createTopFilters() {
      return [
        {
          type: 'INPUT',
          label: '关键字',
          fieldName: 'customerNameOrPhone',
          placeholder: '客户名称/手机号'
        },
        {
          type: 'RANGE_DATE',
          label: '下发/创建时间',
          fieldName: 'dateStart|dateEnd',
          placeholder: '请选择'
        },
        {
          type: 'SELECT',
          label: '线索热度',
          fieldName: 'temperatures',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'INPUT_CASCADER',
          label: '意向车型',
          fieldName: 'inteCarType',
          placeholder: '请选择',
          options: { titles: ['品牌', '车系', '车型', '配置','选装', '颜色'] },
          itemList: []
        },
        {
          type: 'SELECT',
          label: '意向级别',
          fieldName: 'intentLevels',
          placeholder: '请选择',
          itemList: this.createDictList('1519')
        },
        {
          type: 'SELECT',
          label: '所属顾问',
          fieldName: 'consultants',
          placeholder: '请选择',
          itemList: []
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          sorter: true,
          width: 150,
          align: 'center',
          render: props => {
            return <span>{this.preDateHandler(props.row.createdAt)}</span>;
          }
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '联系人姓名',
          dataIndex: 'contactName',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '性别',
          dataIndex: 'gender',
          align: 'center',
          sorter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1002'),
          render: props => {
            return <span>{this.createDictText(props.row.gender, '1002')}</span>;
          }
        },
        {
          title: '手机号码',
          dataIndex: 'mobilePhone',
          sorter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '意向品牌',
          dataIndex: 'inteBrandName',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '意向车系',
          dataIndex: 'inteCarSeriesName',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '意向车型',
          dataIndex: 'inteCarTypeName',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '意向级别(当前)',
          dataIndex: 'intentLevel',
          sorter: true,
          filter: true,
          align: 'center',
          width: 180,
          filterType: 'checkbox',
          filterItems: this.createDictList('1519'),
          render: props => {
            return <span>{this.createDictText(props.row.intentLevel, '1519')}</span>;
          }
        },
        {
          title: '是否下发',
          dataIndex: 'manufacturerIssue',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.manufacturerIssue, '1004')}</span>;
          }
        },
        {
          title: '是否进店',
          dataIndex: 'shop',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input',
          render: props => {
            return <span>{props.row.shop == true ? '是' : '否'}</span>;
          }
        }
      ];
    },
    selectChangeHandle(rows) {
      console.log('rows', rows, rows.length);
      // if (!rows.length) return;
      this.selectedRows = [...rows];
    },
    // 加入合并列表
    mergeListHandle() {
      // console.log('加入合并列表')
      if (!this.selectedRows.length) {
        this.$message.info('请先选择客档');
      } else {
        //多条O级线索处理
        let newArr = []
        this.selectedRows.forEach(item =>{
          if(item.intentLevel === 15191008){
            newArr.push(item)
          }
        })
        console.log('newArr.length',newArr.length )
        if(newArr.length >1 ){
          this.$message.info('已有O级潜客，不支持2个及以上O级潜客合并')
          return
        }
        console.log('合并的数据', this.selectedRows);
        this.$message.success('已加入合并列表');
        // this.willingToMergeData.push(...this.selectedRows);
        this.willingToMergeData = this.selectedRows;
        this.willingToMergeData = this.willingToMergeData.filter((item, index, array) => {
          return array.findIndex(el => el.customerBusinessId == item.customerBusinessId) === index;
        });
      }
      console.log('合并列表的数据', this.willingToMergeData);
    },
    selected(arr) {
      console.log('未移除数据', arr);
      let nArr = [];
      this.selectedRows.map(x => {
        arr.map(y => {
          if (x.potentialCustomersId == y.potentialCustomersId) {
            nArr.push(x);
          }
        })
      });
      this.selectedList = nArr;
      this.willingToMergeData = [];
      this.willingToMergeData.push(...arr);
      this.willingToMergeData = this.willingToMergeData.filter((item, index, array) => {
        return array.findIndex(el => el.customerBusinessId == item.customerBusinessId) === index;
      });
    },
    // 合并
    mergeHandle() {
      console.log('合并');
      this.visible = true;
    },
    changeHandle(val) {
      console.log('val', val);
      this.fetchParams = Object.assign({ allot: 3 }, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.willingToMergeData = [];
        this.fetchParams = { ...this.fetchParams };
      }
    },
    // 日期预处理
    preDateHandler(val, formatCode = 'YYYY-MM-DD HH:mm:ss') {
      let resultDate = val ? moment(Number(val)).format(formatCode) : val;
      if ((resultDate == 'Invalid date' || resultDate == 'Invalid Date') && val) {
        resultDate = moment(val).format(formatCode);
      }
      return resultDate;
    }
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  }
};
</script>

<style lang="less" scoped>
</style>
